package com.shop.milk_tea_shop.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.shop.milk_tea_shop.common.CodeEnum;
import com.shop.milk_tea_shop.common.GlobalInfo;
import com.shop.milk_tea_shop.common.PageInfo;
import com.shop.milk_tea_shop.common.Result;
import com.shop.milk_tea_shop.entity.UserInfo;
import com.shop.milk_tea_shop.mapper.UserInfoMapper;
import com.shop.milk_tea_shop.request.PagedRequest;
import com.shop.milk_tea_shop.service.UserInfoService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yjw
 * @since 2024-06-16
 */
@Service
@Slf4j
public class UserInfoServiceImpl extends ServiceImpl<UserInfoMapper, UserInfo> implements UserInfoService {

    @Autowired
    UserInfoMapper userInfoMapper;

    @Override
    public Result<List<UserInfo>> paged(PagedRequest request) {
        Page<UserInfo> page = new Page<>(request.getPageNum(), request.getPageSize());
        Page<UserInfo> pageResult = userInfoMapper.selectPage(page, Wrappers.emptyWrapper());
        PageInfo pageInfo = new PageInfo(pageResult.getCurrent(), pageResult.getSize(), pageResult.getTotal());
        GlobalInfo globalInfo = new GlobalInfo(pageInfo);
        return new Result<>(CodeEnum.SUCCESS.getMsg(), CodeEnum.SUCCESS, pageResult.getRecords(), globalInfo);
    }

    @Override
    public Result<UserInfo> add(UserInfo userInfo) {

        UserInfo result = this.selectByTel(userInfo);
        if(result!=null) {
            return new Result<>(CodeEnum.SUCCESS.getMsg(), CodeEnum.SUCCESS, result, new GlobalInfo());
        }else {
            int id = userInfoMapper.insert(userInfo);
            UserInfo res = this.selectByTel(userInfo);
            return new Result<>(CodeEnum.SUCCESS.getMsg(), CodeEnum.SUCCESS, res, new GlobalInfo());
        }
    }

    @Override
    public UserInfo selectByTel(UserInfo userInfo) {
        LambdaQueryWrapper<UserInfo> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotEmpty(userInfo.getUserTel()), UserInfo::getUserTel, userInfo.getUserTel());
        UserInfo result = userInfoMapper.selectOne(queryWrapper);
        return result;
    }
}
